/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.service.theme.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.grayrabbit.cms.constant.ConstantTheme;
import org.grayrabbit.cms.dao.site.SiteDao;
import org.grayrabbit.cms.dao.theme.ThemeDao;
import org.grayrabbit.cms.entity.OperLog;
import org.grayrabbit.cms.entity.Theme;
import org.grayrabbit.cms.service.theme.ThemeService;
import org.grayrabbit.cms.util.FilePathSptUtil;
import org.grayrabbit.cms.vo.theme.ThemeBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.grayrabbit.dao.util.Page;
import org.grayrabbit.service.impl.GenericServiceImpl;
/**
 * <b>OperLog</b>的service实现类，事务加此处：





 * @version 1.0,创建时间: 2011-05-16 15:57:47  
 */
@Service
@Transactional
public class ThemeServiceImpl extends GenericServiceImpl implements ThemeService {
	/**
	 * 注入dao层：
	 */
	@Autowired
	@Qualifier("themeDaoImpl")
	private ThemeDao themeDao;
	
	@Autowired
	@Qualifier("siteDaoImpl")
	private SiteDao siteDao;
	
	/**
	 * 此方法执行时为只读事务：
	 * @see ThemeService#getOperLog(String)
	 */
	@Transactional(readOnly=true)
	public Theme getTheme(final String themeId){
		Theme theme = themeDao.findById(themeId);
		themeDao.initialize(theme);
		return theme;
	}
	
	/**
	 * @see ThemeService#delete(String)
	 */
	@Transactional
	public void delete(final Theme theme) {
		themeDao.makeTransient(theme);
	}
	
	/**
	 * @see ThemeService#save(OperLog)
	 */
	@Transactional
	public void save(final Theme theme) {
		themeDao.makePersistent(theme);		
	}
	
	/**
	 * 此方法执行时为只读事务：
	 * @see ThemeService#getPage(ThemeBean)
	 */
	@Transactional(readOnly=true)
	public Page<Theme> getPage(final ThemeBean themeBean){
		Page<Theme> page =  new Page<Theme>();
		page.setTotal(themeDao.count(themeBean));
		page.setResult(themeDao.findByQc(themeDao.assembly(themeBean)));
		return page;
	}

	/**
	 * 此方法执行时为只读事务：
	 * @see ThemeService#list(Page, ThemeBean)
	 */
	public void list(Page<Theme> page, ThemeBean themeBean) {
		if(page==null)
			return;
		if(page.isAutoCount()){
			page.setTotal(themeDao.count(themeBean));
		}
		page.setResult(themeDao.findByPage(page,themeBean));
	}
	
	/**
	 * 根据主键id列删除，批量删除OperLog
	 * @see ThemeService#delete(String[])
	 */
	public void delete(final String[] key) {
		int i =0;
		for(String id : key){
			themeDao.makeTransient(themeDao.findById(id));
			i++;
			if(i==MAX_CLEAR)
				themeDao.clear();
		}
		
	}

	@Transactional(readOnly=true)
	public List<Theme> findAll() {
		return themeDao.findAll();
	}

	public void saveAll(List<Theme> addList) {
		if(addList == null || addList.isEmpty()) return ;
		for(Theme t:addList){
			themeDao.makePersistent(t);
		} 		
	}

	public void deleteAll(List<Theme> delList) {
		if(delList == null || delList.isEmpty()) return ;
		for(Theme t:delList){
			themeDao.makeTransient(t); 
		 }
		
	}

	public List<Theme> findAllRealUsableTheme(String absoluteThemePath) {
		if(StringUtils.isBlank(absoluteThemePath)) return null;
		File rootThemefile = new File(absoluteThemePath);
		
		Theme t = null;
		
		List<Theme> fileTheme = new ArrayList<Theme>();
		if(!rootThemefile.exists() || !rootThemefile.isDirectory()){
			rootThemefile.mkdirs();
		}else if(rootThemefile.isDirectory()){
			File[] files = rootThemefile.listFiles(new FileFilter() {				
				public boolean accept(File f) {
					if(f.isDirectory()){
						return true;
					} 
					return false;
				}
			});
			
			List<Theme> dbList = findAll(); //数据库的theme
			List<Theme> exitList = new ArrayList<Theme>();  //存在数据库的
			
			for(File f : files){
				if(ConstantTheme.CUSTOM.equalsIgnoreCase(f.getName()) 
						|| ConstantTheme.MACRO.equalsIgnoreCase(f.getName())
						|| ConstantTheme.COMPONENT.equalsIgnoreCase(f.getName()) )
					continue;
				t = new Theme();
				t.setThemeName(f.getName());
				t.setThemeDesc(getDescContent(f.getAbsolutePath()
						+ FilePathSptUtil
								.padLeftSpt(ConstantTheme.DESC_FILE_NAME)));
				t.setThemeStatus(true);
				for (Theme e : dbList) {
					if(f.getName().endsWith(e.getThemeName())){
						t.setThemeStatus(e.getThemeStatus());
						t.setThemeId(e.getThemeId()); 
						exitList.add(t);
					}
				}
			 
				fileTheme.add(t);
			}			
			
		   // 处理 数据库多余删  缺少的 添加
			checkTheme(fileTheme,dbList,exitList);
			
		}
		return themeDao.findAll();
	}
	
	private String  getDescContent(String absolutePath){
		if(StringUtils.isBlank(absolutePath)) return null;
		File file = new File(absolutePath);
		String  content = null;
		if(file.exists() && file.isFile()){
			try {
				content = FileUtils.readFileToString(file, "utf-8");			
				if(StringUtils.isNotBlank(content) && content.length()>1){
					content = content.substring(1);					
				}				
				if(StringUtils.isNotBlank(content) && content.length()>512){
					content = content.substring(0, 510);
				}
			} catch (IOException e) {
				content=null;
				e.printStackTrace();
			}
		}
		return content;
	}
	
	/**  
	 * 文件系统为基础，（数据库中有，文件中没有的删除，反之，新增）
	 * @param fileTheme 文件系统存在的THeme
	 * @param exitList2 
	 * @param dbList 
	 */
	private void checkTheme(List<Theme> fileTheme, List<Theme> dbList, List<Theme> exitList){		 
		List<Theme> addList = null;
		List<Theme> delList = null;
		if(fileTheme==null || fileTheme.isEmpty()){
			addList=null;
			delList=dbList;
		}else if(dbList == null || dbList.isEmpty()){
			addList=fileTheme;
			delList=null;
		}else if(fileTheme !=null && !fileTheme.isEmpty() && dbList != null && !dbList.isEmpty()){
			fileTheme.removeAll(exitList);
			addList = fileTheme;
			delList = getDelListInfo(dbList,exitList); //获取数据库要删除的信息
		}
		saveAll(addList);
		deleteAll(delList);
	}
	
	private List<Theme> getDelListInfo(List<Theme> dbList, List<Theme> exitList) {
		if(dbList ==null || dbList.isEmpty() || exitList == null || exitList.isEmpty())	
			return null;
		List<Theme> delList = new ArrayList<Theme>();
		for(Theme t :dbList){
			for(Theme e :exitList){
				if(t.getThemeId().equals(e.getThemeId())){
					delList.add(t);
				}
			}
		}
		dbList.removeAll(delList);
		return dbList;
	}

	/**批量启用禁用
	 * @param objectIds
	 */
	@Transactional
	public boolean changeThemeStatus(String objectId) {
	     if(StringUtils.isBlank(objectId)) return false;
	     
	     Theme t =themeDao.findById(objectId); 
	     boolean objectFlag = false;
	     if(t.getThemeStatus()==null || !t.getThemeStatus()){
    		 objectFlag=true;
    	 }else{
    		 objectFlag=false;
    	 }
    	 t.setThemeStatus(objectFlag);	    	 
    	 themeDao.makePersistent(t);
	     return objectFlag;
	} 
	public boolean checkUsableTheme(String themeName){		
		if(StringUtils.isBlank(themeName)) return false;
		return themeDao.checkUsableTheme(themeName);
	}

	public boolean findSiteByTheme(String themeId) {
		Theme t =themeDao.findById(themeId); 
		if(t.getThemeStatus().booleanValue()){
			return siteDao.findSiteByTheme(t.getThemeName());
		}
		return false;
	}
 
}